$(document).ready( function() {
	
	//获取项目名
	var contextPath = document.location.pathname; 
	var index =contextPath.substr(1).indexOf("/"); 
	contextPath = contextPath.substr(0,index+1); 

	var isReading = false; // 是否处于监视用户输入状态
	var proArr = new Array()// 定义一个数组，用来存储产品实体
	var addPageCount = 1;// 初始化为1
	var len = 0;// 标记数组的长度，删除时-1
	
	/**
	 * 清空table（除了table的首行）
	 * */
	function clearItemTable() {
		$("#itemsTable tr:not(:first)").remove();
	}

	/**
	 * 保存与修改数据
	 */
	$("#optBtnGR").delegate('#saveBtnGR', 'click', function() {

		$("#giftGroup").attr("method", "post");

		var giftId= $("#giftId").val();
		$("#giftGroup").attr("action", contextPath+"/manage/giftGroup/saveGR.do?giftId="+giftId);
		
		clearItemTable();//清空table
		var itemTable = $("#itemsTable");
			for(i=0;i<proArr.length;i++){
				
				lookItemContent(itemTable,proArr[i],i);
			}
		
		$("#giftGroup").submit();
		

	});
	
	
	/**
	 * 删除添加的记录
	 */
	$("#itemsTable").delegate(
		"button[name='delItem']",
		'click',
		function() {
			if (confirm("是否要删除该记录?") == true) {
				var trId = $(this).attr("rowId");
				var deltrId = $(this).attr("delId");
				var itemId = $("#id_" + deltrId).val();
				var id = $(this).parent().parent().attr("id");
				if (itemId == null || itemId == ""|| itemId == "undefined") {
					proArr.splice(trId,1);
					$(this).parent().parent().remove();
					len = proArr.length;
					getQuery(len);
				} else {
					var delUrl = contextPath+"/manage/giftGroup/delItemById.do";
					$.ajax({
						url : delUrl,
						dataType : 'text',
						data : {
							id : itemId
						},
						cache : false,
						success : function(data) {
							proArr.splice(trId,1);
							$(this).parent().parent().remove();
							len = proArr.length;
							getQuery(len);
							return;
						},
						error : function(html) {
							alert("delete Data failly");
							return;
						}
					});
				}
			}
	
		});
	/**
	 * 
	 * 添加产品
	 */
	$("#searchInfor").delegate('#addItem', 'click', function() {
		//clearArrAll();//清空数组
		var proDetaiId = $("#proRules").val();
		if (proDetaiId != -1) {
			var loadProductUrl = contextPath+"/manage/giftGroup/loadProduct.do?id=" + proDetaiId;
			$.ajax({
				url : loadProductUrl,
				dataType : "json",
				success : function(data) {
					if (data != null) {
						var itemTable = $("#itemsTable");//这个方法用来判断这个产品是否存在
						if (isItemInOrder(itemTable,data) <= 0) {
							pushGiftOrder(data);//这个方法用来内分页
						} else {
							alert("[" + data.proCode + "]" + data.proName + " 已存在于组合中..");
						}
						return;
					}
				},
				error : function(data) {
					alert("加载数据出错");
					return;
				}
			});
		} else {
			alert("请选择要添加的产品规格！");
		}
	
	});
	
	
	/**
	 * 分页函数
	 */
	function getQuery(len) {
		/**
		 * 添加的内分页
		 */
		if (len <= 5) {
			addPageCount = 1;
		} else {
			if (len % 5 == 0) {
				addPageCount = len / 5;
			} else {
				addPageCount = Math.floor((len / 5)) + 1;
			}
		}
		$('#itemPagination')
				.jqPaginator(
						{
							totalPages : addPageCount,
							visiblePages : 10,//可以看到的页数
							currentPage : 1,
							prev : '<li class="prev"><a href="javascript:void(0);">上一页</a></li>',
							page : '<li class="page"><a href="javascript:void(0);">{{page}}</a></li>',
							next : '<li class="next"><a href="javascript:void(0);">下一页</a></li>',
							onPageChange : function(num, type) {
								clearItemTable();
								var itemTable = $("#itemsTable");
								var start = num * 5 - 5;
								var end = num * 5;
								var groupId = $("#groupId").val();
								var idx = 0;
								for (i = start; i < proArr.length; i++) {
									if(idx<5){
										lookItemContent(itemTable,proArr[i],i);
										idx++;
									}
							}
						}
					});
		return true;
	}
	
	
	
	/**修改*/
	/*多余的框要给其赋值；否则在添加产品所有除了产品本身的字段外，其他的都没有值*/
	function lookItemContent(itemTable, data,rowNum) {
		var gdId= $("#giftdeId").val();
		var rowContent = "<tr id="
		+ data.proId
		+ ">" 
		//产品规格编号
		+ "<td style='text-align: center;'>" 
		+ "<input type='text'  id='proCode_"
		+ data.id + "'  name='giftGroupVO[" + rowNum
		+ "].proCode' itemName='proCode' value='"
		+ data.proCode
		+ "' readonly='readonly' />";
		if(data.id==null||data.id=='undefined'){
			rowContent = rowContent
			//产品组合id
			+ "<input type='hidden'  id='id_"
			+ data.id + "'  name='giftGroupVO[" + rowNum
			+ "].id' itemName='id' />" ;
		}
		else{
			rowContent = rowContent
			//产品组合id
			+ "<input type='hidden'  id='id_"
			+ data.id + "'  name='giftGroupVO[" + rowNum
			+ "].id' itemName='id' value='"+data.id+"'/>" ;
			
		}
		rowContent = rowContent
		//产品规格的id
		+ "<input type='hidden' id='proId_"
		+ data.id + "'  name='giftGroupVO[" + rowNum
		+ "].proId' itemName='proId' value='"
		+ data.proId + "' />" 
		
		//礼品规格的id
		+"<input type='hidden' id='gdeId_' name='giftGroupVO[" + rowNum
		+ "].gdeId' itemName='gdeId' value='"+gdId+"'/>"
		+ "</td>";
		

		//产品名称
		rowContent = rowContent
		+ "<td style='text-align: center;'>" 
		+ "<input id='proName_"
		+ data.id + "' type='text' name='giftGroupVO["
		+ rowNum
		+ "].proName' itemName='proName' value='"
		+ data.proName + "' readonly='readonly' />" 
		+ "</td>";
		
		//产品规格名称
		rowContent = rowContent
		+ "<td style='text-align: center;'>" 
		+ "<input id='ruleName_"
		+ data.id + "' type='text' name='giftGroupVO["
		+ rowNum
		+ "].ruleName' itemName='ruleName' value='"
		+ data.ruleName + "' readonly='readonly' />" 
		+ "</td>";

		//产品单价
		rowContent = rowContent
		+ "<td style='text-align: center;'>" 
		+ "<input id='enterPrice_"
		+ data.id + "' type='text' name='giftGroupVO["
		+ rowNum
		+ "].enterPrice' itemName='enterPrice' value='"
		+ data.enterPrice + "' readonly='readonly' />" 
		+ "</td>";
	
		if(data.totalGR == null || data.totalGR == 'undefined' ){
			//产品数量
			rowContent = rowContent
			+ "<td style='text-align: center;'>" 
			+ "<input  id='totalGR_"
			+ data.id + "' type='text' name='giftGroupVO["
			+ rowNum + "].totalGR' rowId='" + rowNum
			+ "' itemName='totalGR' />" 
			+ "</td>";
			
			//总价
			rowContent = rowContent
			+ "<td style='text-align: center;'>" 
			+ "<input id='summeryGR_"
			+ data.proId + "' type='text' name='giftGroupVO["
			+ rowNum + "].summeryGR' rowId='" + rowNum
			+ "' itemName='summeryGR' readonly='readonly' />" 
			+ "</td>";
			
			
		}
		else{
			//产品数量
			rowContent = rowContent
			+ "<td style='text-align: center;'>" 
			+ "<input  id='totalGR_"
			+ data.id + "' type='text' name='giftGroupVO["
			+ rowNum + "].totalGR' rowId='" + rowNum
			+ "' itemName='totalGR' value='"+data.totalGR+"'/>" 
			+ "</td>";
			
			//总价
			rowContent = rowContent
			+ "<td style='text-align: center;'>" 
			+ "<input id='summeryGR_"
			+ data.proId + "' type='text' name='giftGroupVO["
			+ rowNum + "].summeryGR' rowId='" + rowNum
			+ "' itemName='summeryGR' value='"+data.summeryGR+"' readonly='readonly' />" 
			+ "</td>";
		}
		if(data.descriptionGR == null || data.descriptionGR == 'undefined'){
			//说明
			rowContent = rowContent
			+ "<td style='text-align: center;'>" 
			+ "<input id='descriptionGR_"
			+ data.id + "' type='text' name='giftGroupVO["
			+ rowNum + "].descriptionGR' rowId='" + rowNum
			+ "' itemName='descriptionGR' />" 
			+ "</td>";
			
		}else{
			//说明
			rowContent = rowContent
			+ "<td style='text-align: center;'>" 
			+ "<input id='descriptionGR_"
			+ data.id + "' type='text' name='giftGroupVO["
			+ rowNum + "].descriptionGR' rowId='" + rowNum
			+ "' itemName='descriptionGR' value='"+data.descriptionGR+"'/>" 
			+ "</td>";
			
		}
		if(data.note == null || data.note == 'undefined'){
			//备注
			rowContent = rowContent
			+ "<td style='text-align: center;'>" 
			+ "<input id='note_"
			+ data.id + "' type='text' name='giftGroupVO["
			+ rowNum + "].note' rowId='" + rowNum
			+ "' itemName='note' />" 
			+ "</td>";
		}else{
			//备注
			rowContent = rowContent
			+ "<td style='text-align: center;'>" 
			+ "<input id='note_"
			+ data.id + "' type='text' name='giftGroupVO["
			+ rowNum + "].note' rowId='" + rowNum
			+ "' itemName='note' value='"+data.note+"'/>" 
			+ "</td>";
		}
		
		
		//操作
		rowContent = rowContent
		+ "<td style='text-align: center;'>" 
		+ "<button name='delItem' rowId='"+rowNum+"' delId='"
		+ data.id+ "' type='button'>删除</button>" 
		+ "</td>";
	
		rowContent = rowContent + "</tr>";
		itemTable.append(rowContent);
		rowNum++;
	}
	
	/**
	 * 清空数组
	 */
	function clearArrAll(){
		if(proArr.length>0){
			proArr.splice(0,proArr.length);
		}
	}
	
	/**
	 * 判断列表当中是否已经存在重复的产品
	 */
	function isItemInOrder(itemTable, data) {
		var j = 0;
		for (var i = 0; i < proArr.length; i++) {
			var g = proArr[i];
			if (g == null || g == "" || g == "undefined") {
				continue;
			}
			if (data.proCode == g.proCode) {
				j++;
			}
		}
		return j;
	}
	
	/**
	 * 存储产品
	 */
	function pushGiftOrder(data) {
		proArr.push(data);
		len=proArr.length;
		getQuery(len);// 分页
	}
	
	
	/**
	 * 组合管理按钮事件
	 */
	
	$("#gdList").delegate('#viewGroup', 'click', function() {
		clearArrAll();//清空数组
		clearItemTable()//清空table
		//产品规格的id
		var gdId =$(this).attr("objId");
		//var giftId = $("#giftId").val();
		
		$("#giftdeId").val(gdId);
		//根据礼品规格的ID找到产品组合的列表
		var queryUrl = contextPath+"/manage/giftGroup/queryGroup.do";
		if (gdId != "") {
			clearArrAll();//清除数组
			$.ajax({
				url : queryUrl,
				type : "POST",
				dataType : 'json',
				data : {
					id : gdId,
				},
				cache : false,
				success : function(data) {
					var giftId=data.giftId;
					var gdId=data.gdId;
					$("#giftId").val(giftId);
					$("#giftdeId").val(gdId);
					
					len = data.resultList.length;
					for (i = 0; i < len; i++) {
						var result = data.resultList[i];
						proArr.push(result);
					}
					getQuery(len);
				},
				error : function(html) {
					alert("出错了");
					return;
				}
			});
		} else {
			/**
			 * 添加的内分页
			 */
			$('#itemPagination').jqPaginator({
				totalPages : addPageCount,
				visiblePages : 10,
				currentPage : 1,
				prev : '<li class="prev"><a href="javascript:void(0);">上一页</a></li>',
				page : '<li class="page"><a href="javascript:void(0);">{{page}}</a></li>',
				next : '<li class="next"><a href="javascript:void(0);">下一页</a></li>',
				onPageChange : function(num,type) {
					clearItemTable();
					getQuery(len);
				}
			});
		}
		$("#group").modal('show');
		
	});
	//搜索框
	$("#searchInfor").delegate('#itemName', 'change', function() {
					if (!isReading) {
						clearSuggest();
						var itemStr = $('#itemName').val();
//						alert("苹果===>"+itemStr);
						var ajaxUrl = encodeURI(contextPath+"/manage/giftGroup/queryProducts.do?condition="+ itemStr);
						$.ajax({
							url : ajaxUrl,
							dataType : "json",
							condition : itemStr,
							success : function(data) {
								if (data != null&& data.result.length > 0) {
									clearSuggest();
									for (i = 0; i < data.result.length; i++) {
										var result = data.result[i];
										createSuggest(result);
									}
									displaySuggest();
								} else {
									hiddenSuggest();
								}
								isReading = false;
							},
							error : function(data) {
								alert("加载数据出错");
								return;
							}
						});
					}
				});
	$("#searchInfor").delegate('#itemName', 'keyup', function() {
		if (!isReading) {
			clearSuggest();
			var itemStr = $('#itemName').val();
//			alert("苹果ss===>"+itemStr);
			counter = itemStr.length;
//			if (counter == 3) {
				var ajaxUrl = encodeURI(contextPath+"/manage/giftGroup/queryProducts.do?condition=" + itemStr);
				$.ajax({
					url : ajaxUrl,
					dataType : "json",
					condition : itemStr,
					success : function(data) {
						if (data != null && data.result.length > 0) {
							for (i = 0; i < data.result.length; i++) {
								var result = data.result[i];
								createSuggest(result);
							}
							displaySuggest();
						} else {
							hiddenSuggest();
						}
						isReading = false;

					},
					error : function(data) {
						alert("加载数据出错");
						return;
					}
				});
			}
//		}
	});
	
	
	
	/**
	 * 根据单价和数量计算出总价
	 */
	$("#itemsTable") .delegate("input[itemName='totalGR']", 'change', function() {
		var totalGR = $(this).val();
		var enterPrice = $(this).parent().parent().children().children("input[itemName='enterPrice']").val();
		var id = $(this).parent().parent().attr("id");
		var trId = $(this).attr("rowId");
		if(totalGR<=0){
			alert("数量最小值为1");
			$(this).val(1);
			totalGR = $(this).val();
		}
		$("#summeryGR_" + id).val(enterPrice * totalGR);
		var ele = proArr[trId];
		ele.totalGR = totalGR;
		ele.summeryGR = enterPrice * totalGR;
		proArr.splice(trId, 1, ele);
	});

	/**
	 * 给总价赋值
	 * */
	$("#itemsTable") .delegate("input[itemName='totalGR']", 'blur', function() {
		var totalGR = $(this).val();
		var enterPrice = $(this).parent().parent().children().children("input[itemName='enterPrice']").val();
		var id = $(this).parent().parent().attr("id");
		var trId = $(this).attr("rowId");
		if(totalGR<=0){
			alert("数量最小值为1");
			$(this).val(1);
			totalGR = $(this).val();
		}
		$("#summeryGR_" + id).val(enterPrice * totalGR);
		var ele = proArr[trId];
		ele.totalGR = totalGR;
		ele.summeryGR = enterPrice * totalGR;
		proArr.splice(trId, 1, ele);
	});
	
	/*赋值说明descriptionGR*/
	$("#itemsTable") .delegate("input[itemName='descriptionGR']", 'blur', function() {
		var descriptionGR = $(this).val();
		var id = $(this).parent().parent().attr("id");
		var trId = $(this).attr("rowId");
		$("#descriptionGR" + id).val(descriptionGR);
		var ele = proArr[trId];
		ele.descriptionGR = descriptionGR;
		proArr.splice(trId, 1, ele);
	});
	/*赋值备注note*/
	$("#itemsTable") .delegate("input[itemName='note']", 'blur', function() {
		var note = $(this).val();
		var id = $(this).parent().parent().attr("id");
		var trId = $(this).attr("rowId");
		$("#note" + id).val(note);
			var ele = proArr[trId];
			ele.note = note;
			proArr.splice(trId, 1, ele);
	});
	
	
	
	
	/**赋值给搜索框*/
	$("#searchInfor").delegate('[name="out"]', 'click', function() {
		$("#proRules").find("option").remove();
		setSuggest(this);

	});
	
	/**获取要赋值的搜索框的name值*/
	function setSuggest(src) {
		document.getElementById("itemName").value = src.innerHTML;
		document.getElementById("itemId").value = src.id;
		var itemId = $("#itemId").val();
		
		getOrderDetail(itemId);
		hiddenSuggest();
	}
	
	/**
	 * 获取产品规格
	 */
	function getOrderDetail(proId){
		var optStr = null;
		var detailsUrl= contextPath + "/manage/giftGroup/queryProDetails.do?proId="+proId;
		$.ajax({
			url : detailsUrl,
			dataType : "json",
			success : function(data) {
				for(i=0;i<data.resultList.length;i++){
					var result = data.resultList[i];
					optStr =optStr+ "<option value='" + result.id + "'>"
					+ result.ruleName + "</option>";
				}
				$("#proRules").append(optStr);
			},
			error : function(data) {
				alert("加载数据出错");
				return;
			}
		});
		
	}
					
	/**
	 * 根据不同单据类型，把查出来的规格数据集合放入select组件中
	 */
	function createSuggest(data) {
		var sDiv = "<div name='out' class='out' onmouseover=\"this.className='over'\" "
				+ "onmouseout=\"this.className='out'\" id='"
				+ data.id + "'>" + data.proName + "</div>";
		document.getElementById("selectItem").innerHTML += sDiv;
	}
	/** 显示提示信息 */
	function displaySuggest() {
		document.getElementById("selectItem").style.display = "";
	}
	/** 隐藏提示信息 */
	function hiddenSuggest() {
		document.getElementById("selectItem").style.display = "none";
	}
	/** 清空提示信息 */
	function clearSuggest() {
		document.getElementById("selectItem").innerHTML = "";
	}

});

/**
 * 刷新页面
 * */
function refresh() {
	window.location.reload();
}
